<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import { debounce } from '@/utils'

const animationDuration = 2000

export default {
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    },
    profitData: {
      type: Array,
      default() {
        return [0, 0, 0]
      }
    }
  },
  data() {
    return {
      chart: null
    }
  },
  mounted() {
    this.initChart()
    this.__resizeHandler = debounce(() => {
      if (this.chart) {
        this.chart.resize()
      }
    }, 100)
    window.addEventListener('resize', this.__resizeHandler)
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    window.removeEventListener('resize', this.__resizeHandler)
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')

      this.chart.setOption({
        title: {
          text: '任期收益',
          textStyle: {
            color: '#333333',
            fontWeight: 'bold'
            // lineHeight: 24
            // textShadowOffsetX: '190px',
            // textShadowOffsetY: '1px'
          },
          textAlign: 'auto',
          textVerticalAlign: 'auto'
          // left: 'center',
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: { // 坐标轴指示器，坐标轴触发有效
            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
          },
          formatter: '{b0}：{c0}%'
        },
        grid: {
          // top: 45,
          left: '3%',
          right: '4%',
          // bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: ['任期收益', '同类平均', '沪深300'],
          axisTick: {
            alignWithLabel: true
          }
        },
        yAxis: {
          type: 'value',
          axisTick: {
            show: false
          },
          axisLabel: {
            formatter: '{value}%'
          }
        },
        series: {
          name: '',
          type: 'bar',
          barWidth: '50%',
          data: [
            {
              value: this.profitData[0],
              itemStyle: {
                color: 'rgb(124, 181, 236)'
              }
            },
            {
              name: '同类平均',
              value: this.profitData[1],
              itemStyle: {
                color: 'rgb(65, 76, 123)'
              }
            },
            {
              value: this.profitData[2],
              itemStyle: {
                color: 'rgb(247, 163, 92)'
              }
            }
          ],
          animationDuration
        }
      })
    }
  }
}
</script>
